//引入express
const express = require('express')
//创建router
const router = express.Router()
//引入中间件
var multiparty = require('multiparty');

// var jwt = require('jsonwebtoken');
var Ctoken = require('../public/token');


//引入mysql
const mysql = require('mysql')
const { UCS2_ICELANDIC_CI } = require('mysql/lib/protocol/constants/charsets')
//引入数据库信息
const db = require('../db')
//引入sql文件，使用查询语句
const sql = require('../sql');
// const { forEach } = require('core-js/core/array');

//创建连接
const connection = mysql.createConnection(db.mysql)
connection.connect()

//时间转化为字符串时间
function formatDateTime(date) {
    var y = date.getFullYear();  
        var m = date.getMonth() + 1;  
        m = m < 10 ? ('0' + m) : m;  
        var d = date.getDate();  
        d = d < 10 ? ('0' + d) : d;  
        var h = date.getHours();  
        h=h < 10 ? ('0' + h) : h;  
        var minute = date.getMinutes();  
        minute = minute < 10 ? ('0' + minute) : minute;  
        var second=date.getSeconds();  
        second=second < 10 ? ('0' + second) : second;  
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
}

//字符串时间转化为时间
function convertDateFromString(dateString) {
    if (dateString) { 
        var arr1 = dateString.split(" "); 
        var sdate = arr1[0].split('-'); 
        var hour =arr1[1].split(':')    
        var date = new Date(sdate[0], sdate[1]-1, sdate[2],hour[0],hour[1],hour[2]); 
        return date;
        } 
}
                   
//用户登录请求
router.post('/login', (req, res) => {
    //查询所有用户
    connection.query(sql.user.selUser, [req.body.username],(err, result)=> {
        //有异常 抛出异常信息
        if(err) { throw err }      
        //判断输入的用户是否在数据库中
        if (result.length > 0) {
            //用户存在，判断密码是否正确
            if (req.body.password === result[0].password) {
                //生成token
                Ctoken.setToken(req.body.username).then((data) => {
                    res.send({
                        isRight: true,
                        msg: '登录成功！',
                        token: data,
                        type: result[0].type,
                        userId:result[0].id
                    })
                    return
               })   
            } else {
                res.send({
                    isRight: false,
                    msg:'密码错误！'
                })
                return
            }
        } else {
            res.send({
                isRight: false,
                msg:'用户不存在'
            }) 
            return
        }
    })

})

//获取用户头像
router.get('/getUserPortrait', (req, res) => {
    connection.query(sql.user.selUserPortrait, [req.query.userId], (err, result) => {
        if (err) throw err;
        // console.log(result)
        res.json(result)
    })
})

//普通用户注册
router.post('/normalRegister', (req, res) => {
    //查询所有用户
    connection.query(sql.user.selAllUser, (err, result) => {
        if (err) throw err;
        //判断要注册的用户有没有存在
        if (result.length>0) {
            var findName = result.filter(item => {
                return item.username === req.body.username
            })
            // 判断有没有重复的手机号
            var findPhone = result.filter(item => {
                return item.phone === req.body.phone
            })
            if (findName.length) {
                res.send({
                    isRight: false,
                    msg:'该用户已存在'
                })
                return
            } else if(findPhone.length){
                res.send({
                    isRight: false,
                    msg:'手机号已被注册过了'
                })
                return
            } else {
                const {username,password,paypwd,gender,email,phone,address,type} = req.body
                connection.query(sql.user.normalRegister, [username,password,paypwd,gender,email,phone,address,type], (err1, result1) => {
                    if (err) throw err1;
                    console.log('成功！！！')
                    res.send({
                        isRight: true,
                        msg:'注册成功！！'
                    })
                })
                return
            }
        }
    })
})

//茶商注册
router.post('/merchantRegister', (req, res) => {

    //查询所有用户
    connection.query(sql.user.selAllUser, (err, result) => {
        if (err) throw err;
        //判断要注册的用户有没有存在
        if (result.length>0) {
            var findName = result.filter(item => {
                return item.username === req.body.username
            })
            var findPhone = result.filter(item => {
                return item.phone === req.body.phone
            })
            if (findName.length) {
                res.send({
                    isRight: false,
                    msg:'该茶商已存在'
                })
                return
            } else if(findPhone.length){
                res.send({
                    isRight: false,
                    msg:'手机号已被注册过了'
                })
                return
            } else {
                // console.log(req.body)
                const {username,password,gender,email,phone,address,type,userType} = req.body
                connection.query(sql.user.merchantRegister, [username,password,gender,email,phone,address,type,userType], (err1, result1) => {
                    if (err) throw err1;
                    res.send({
                        isRight: true,
                        msg:'注册成功！！'
                    })
                    return
                })

                return
            }
        }
    })
})

//查询热销商品
router.get('/selHotProduct', (req, res) => {
    connection.query(sql.user.selHotSale, (err, result) => {
        if (err) throw err
        // console.log(result)
        //合并相同的元素
        for (let i = 0; i < result.length-1; i++){
            for (let j = i + 1; j < result.length; j++){
                if (result[i].name === result[j].name) {
                    result[i].number = result[i].number+result[j].number
                    result.splice(j, 1)
                }
            }
        }
        //截取前面三个数据
        result = result.length>=3? result.slice(0, 3):result.length>=2? result.slice(0, 2):result.length>=1?result.slice(0, 1):[]
        let index =1
        result = result.map(item => {
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === '' || item.imgPath ===null?'oolong.jpg':item.imgPath
            item.index = index++
            return item
        })
        
        res.json(result)
    })
})
 
//查询搜索商品
router.get('/selSearchProduct', (req, res) => {
    connection.query(sql.user.selSearchProduct,[`%${req.query.value}%`], (err, result) => {
        if (err) throw err
        //合并相同的元素
        for (let i = 0; i < result.length-1; i++){
            for (let j = i + 1; j < result.length; j++){
                if (result[i].name === result[j].name) {
                    result[i].number = result[i].number+result[j].number
                    result.splice(j, 1)
                }
            }
        }
        //截取前面三个数据
        result = result.length>=5? result.slice(0, 5): result.length>=4? result.slice(0, 4): result.length>=3? result.slice(0, 3):result.length>=2? result.slice(0, 2):result.length>=1?result.slice(0, 1):[]
        let index =1
        result = result.map(item => {
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === '' || item.imgPath ===null?'oolong.jpg':item.imgPath
            item.index = index++ 
            return item
        })
        console.log(result)
        res.json(result)
    })
})

//获取红茶数据
router.get('/blackTea', (req, res) => {
    connection.query(sql.user.blackTea, (err, result) => {
        if (err) throw err;
        var index = 1 
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        console.log(result)
        res.send(result)
    }) 
})

//获取黑茶数据
router.get('/darkTea', (req, res) => {
    connection.query(sql.user.darkTea, (err, result) => {
        if (err) throw err;
        
        var index = 1 
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        console.log(result)
        res.send(result)
    })
})

//获取绿茶数据
router.get('/greenTea', (req, res) => {
    connection.query(sql.user.greenTea, (err, result) => {
        if (err) throw err;
        
        var index = 1 
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        console.log(result)
        res.send(result)
    })
})

//获取乌龙茶数据
router.get('/oolongTea', (req, res) => {
    connection.query(sql.user.oolongTea, (err, result) => {
        if (err) throw err;
        
        var index = 1 
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        console.log(result)
        res.send(result)
    })
})

//获取白茶数据
router.get('/whiteTea', (req, res) => {
    connection.query(sql.user.whiteTea, (err, result) => {
        if (err) throw err;
        
        var index = 1 
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        console.log(result)
        res.send(result)
    })
})

//获取黄茶数据
router.get('/yellowTea', (req, res) => {
    connection.query(sql.user.yellowTea, (err, result) => {
        if (err) throw err;
        
        var index = 1 
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        console.log(result)
        res.send(result)
    })
}) 

//获取用户支付密码
router.get('/getUserPaypwd', (req, res) => {
    console.log('req.query',req.query)
    connection.query(sql.user.getUserPaypwd, [req.query.userId], (err, result) => {
        if (err) throw err;
        console.log('result',result)
        if (result.length > 0) {
            if (result[0].paypwd === req.query.paypwd) {
                res.json({
                    pwdIsRight: true,
                    msg:'密码正确'
                })
                return
            } else {
                res.json({
                    pwdIsRight: false,
                    msg:'密码错误'
                })
                return
            }
        } else {
            res.json({
                msg:'该用户不存在'
            })
            return
        }
    })
})

//获取用户的余额
router.get('/getUserMoney', (req, res) => {
    // console.log(req.query)
    connection.query(sql.user.getUserMoney, [req.query.userId], (err, result) => {
        if (err) throw err;
        // console.log(result)
        if (parseInt(req.query.money) > result[0].money) {
            res.json({
                isEnough:false
            })
            return
        } else {
            res.json({
                isEnough:true
            })
            return
        }
        // res.json(result)
     })
})

//修改用户金额
router.post('/setMoney', (req, res) => {
    console.log('req.body',req.body)
     
    connection.query(sql.user.setMoney, [req.body.money, req.body.userId], (err, result) => {
        if (err) throw err;
        console.log('修改成功')
        res.json({
            isModify:true
        })
        return
    })
})

//获取用户信息
router.get('/selectUserInfo', (req,res)=> {
    connection.query(sql.user.selUserInfoById, [req.query.userId], (error, result) => {
        if (error) throw error;
        // console.log(result)
        result = result.map(item => {
            item.money = parseFloat(item.money).toFixed(2) + '元'
            item.type = item.type === 1 ? '普通客户' : '商家'
            item.gender = item.gender === 0 ? '男' : '女'
            return item
        })
        res.json(result)
    })
})

//修改用户的支付密码
router.post('/modifyUserPayPwd', (req, res) => {
    connection.query(sql.user.modifyPayPwd, [req.body.newPayPwd, req.body.userId], (err, result) => {
        if (err) throw err;

        res.json({
            isModify: true,
            msg:'修改成功！'
        })
    })
})

//修改个人信息
router.post('/modifyPersonInfo', (req, res) => {
    const {password, gender, email, phone, address, userId } = req.body
    
    //判断修改的手机号是不是已存在
    connection.query(sql.user.selectAllPhone, (err, result) => {
        if (err) throw err;
        console.log(result)
        result = result.find(item => {
            return item.phone === req.body.phone
        })
        console.log(result !== undefined)
        if (result !== undefined) {
            res.json({
                isExist: true,
                msg:'电话号码已存在！！'
            })
        } else {
            connection.query(sql.user.updateUserInfo,  [password, gender, email, phone, address, userId], (err, result1) => {
                 if (err) throw err;
                    res.json({
                    isModify: true,
                    msg:'修改成功！！'
                })
            })
        }
    })
})

//获取用户地址
router.get('/getAddress', (req, res) => {
    connection.query(sql.user.getAddress, [req.query.id], (err, result) => {
        if (err) throw err;
        res.json(result)
    })
})

//获取商家的商品
router.get('/getUserProducts', (req, res) => {
    connection.query(sql.user.getUserProducts, [req.query.userId], (err, result) => {
        if (err) throw err;
        // console.log(result)
        var index = 1
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        res.json(result)
    })
})

//修改库存量
router.post('/updateStore', (req, res) => {
    const {store,teaId} = req.body
    connection.query(sql.user.updateStore, [store, teaId], (err, result) => {
        if (err) throw err;
        res.json({
            isAdd: true,
            msg:'商品库存量添加成功！'
        })
    })
})

//删除商品
router.post('/delTea', (req, res) => {
    console.log(req.body)
    connection.query(sql.user.deleteProduct, [req.body.teaId], (err, result) => {
        if (err) throw err;
        res.json({
            isDel: true,
            msg:'删除成功！！'
        })
    })
})

//发货后修改商家金额
router.post("/modifyMoney", (req, res) => {
    let { money, id } = req.body
    money = parseFloat(money).toFixed(2)
    connection.query(sql.user.modifyMoney, [money, id], (err, result) => {
        if (err) throw err;
        res.json({
           msg:'收款成功！'
       }) 
    })
})

//发货后减少库存
router.post('/declineTeaStore', (req, res) => {
    const { store, teaId } = req.body
    //先查询库存有多少
    console.log(req.body)
    connection.query(sql.user.getStore, [teaId], (err, result) => {
        if (err) throw err;
        if (result[0].store >= store) {
            connection.query(sql.user.declineTeaStore, [store,teaId], (err, result1) => {
                if (err) throw err;
                res.json({
                    ok:true,
                    msg:'库存减少成功!'
                })
                return
            })
        } else {
            res.json({
                ok:false,
                msg:'库存不足了,没办法发货啦!'
            })
            return
        }

    })
})

//添加新的商品
router.post('/addNewTea', (req, res) => {
    connection.query(sql.user.getUserProducts, [req.body.userId], (err, result) => {
        if (err) throw err;
        console.log(req.body)
        const findResult =  result.find(item => {
            return item.name === req.body.newTea.name
        })
        if (findResult) {
            res.json({
                isAdded: true,
                msg:'该商品已上架了！！'
            })
            return
        } else {
            var { name, type, brand, price, industry, store } = req.body.newTea
            price = parseFloat(price)
            store = parseInt(store)
            var {userId} = req.body
            userId = parseInt(userId)
            connection.query(sql.user.addNewTea, [name, type, brand, price,industry, store, userId], (err1, result1) => {
                if (err1) throw err1;
                // console.log(result1)
                res.json({
                    isAdd: false,
                    msg:'商品上架成功！！'
                })
            })
        }

    })

})

//根据id获取销售情况(线形图)
router.get('/getSaleResult', (req, res) => {
    connection.query(sql.user.selSaleResult, [req.query.userId], (err, result) => {
        // console.log(req.query)
        if (err) throw err;
        //保存最终结果数据
        let resultArr = []
        //查询结果第一次遍历
        result.forEach(item => {
            if (resultArr.length === 0) {
                //第一次为空的话，直接添加一个对象元素
                resultArr.push({name:item.name,number:[item.number]})
            } else {
                //查询item有没有在结果数组中
                let index = resultArr.findIndex(item1 => {
                    return item1.name===item.name
                })
                if (index === -1) {
                    //不在的情况，新增一个数组
                    resultArr.push({name:item.name,number:[item.number]})
                } else {
                    resultArr.forEach(item1 => {
                        if (item.name === item1.name) {
                            //在的情况下，向数组的元素对象number 
                            item1.number.push(item.number+item1.number[item1.number.length-1]) 
                        } 
                    })
                }
            }
        });
        res.json(resultArr)
    })
}) 

//根据id获取销售情况(柱状图)
router.get('/getBarSale', (req, res) => {
    connection.query(sql.user.selSaleResult, [req.query.userId],(err, result) => {
        if (err) throw err;
        // console.log(result)
        //保存最终返回结果
        let resultArr = [[], []]
        result.forEach(item => {
            //第一次判断结果是否为空，是空的话，直接添加
            if (resultArr[0].length === 0) {
                resultArr[0].push(item.name)
                resultArr[1].push(item.number)
            } else {
                //查找茶叶名称是否相同
                let index = resultArr[0].findIndex(item1 => {
                    return item1 === item.name
                })
                //没有找到直接添加
                if (index === -1) {
                    resultArr[0].push(item.name)
                    resultArr[1].push(item.number)
                } else {
                    //找到直接修改数量
                    resultArr[1][index] = resultArr[1][index] + item.number
                }
            }
        })       
        res.json(resultArr)
    })
})

//根据id获取销售情况表
router.get('/getSaleCondition', (req, res) => {
    connection.query(sql.user.selSaleCondition, [req.query.userId], (err, result) => {
        if (err) throw err;
        let index = result.length
        result = result.map(item => {
            item.index = index--
            item.buyTime = formatDateTime(item.buyTime)
            item.money = parseFloat(item.money).toFixed(2) + '元'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        }).reverse()
        console.log(result)
        res.json(result)
    })
})

//获取用户上传的图片
router.post('/getPortrait', (req, res) => {
    let form = new multiparty.Form();
   form.uploadDir="../src/assets/img";
   form.keepExtensions=true;   //是否保留后缀
  form.parse(req,function(err,fields,files){  //其中fields表示你提交的表单数据对象，files表示你提交的文件对象
    // console.log(req);
    //   console.log('fields===',fields)
      
    if(err){
      res.json({
        status:"1",
        msg:"上传失败！"+err
      });
    } else {
        
         let arrSrt = files.file[0].path.split('\\');
        let str = arrSrt[arrSrt.length - 1] 
    connection.query(sql.user.modifyPortrait, [str,fields.userId[0]], (err, result) => {
            if (err) throw err;
        console.log(result)
        res.json({ 
            status:"0",
            msg:"上传成功！",
            imgSrc: files.image
          }); 
     })
      
    }
  })  
})

//暴露路由
module.exports = router
